package com.stageauthserver.authserver.controller;

import com.stageauthserver.authserver.service.UserService;
import com.stagecommon.common.dto.SmsCodeReq;
import com.stagecommon.common.pojo.RespBean;
import com.stagecommon.common.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @description：登录控制
 * @author： SAYE
 * @create： 2024/3/26 15:41
 */
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserService userService;

    @PostMapping("/login")
    public RespBean<User> login(@RequestBody SmsCodeReq smsCodeReq) {
        Object o = redisTemplate.opsForValue().get("loginTimes" + smsCodeReq.getPhone());
        if (Objects.equals(5, o)) {
            redisTemplate.expire("loginTimes" + smsCodeReq.getPhone(), 60, TimeUnit.SECONDS);
            return RespBean.operationSuccess("登录频繁，请稍候重试", -10, null);
        }
        String code = String.valueOf(redisTemplate.opsForValue().get("sms:ver:code" + smsCodeReq.getPhone()));
        if (code==null
            ||!Objects.equals(code,smsCodeReq.getCode())){
            return RespBean.operationFail("验证码错误！");
        }

        RespBean<User> userRespBean = userService.checkLogin(smsCodeReq.getPhone());
        User user = userRespBean.getData();
        redisTemplate.opsForValue().set(userRespBean.getTokenValue()+"-roleId",user.getRoleIdList());
        redisTemplate.opsForValue().set(userRespBean.getTokenValue()+"-userId",user.getUserId());
        return userRespBean;
    }
}

